<?php

namespace App\HttpController\Web;

use App\HttpController\BaseController;
use App\Model\UsersModel;
use App\Utility\MiniProgram;
use Carbon\Carbon;

class AuthController extends BaseController {

    public function login(){
        $request = $this->request();
        $code = $request->getRequestParam('code');
        $mini = new MiniProgram();
        $session = $mini->session($code);
        $model = new UsersModel();
        $user = $model->where('openid',$session['openid'])->first();
        if(empty($user)){
            //新增用户
            $insert = [
                'openid' => $session['openid'],
                'register_at' => Carbon::now(),
                'login_at' => Carbon::now(),
            ];
            $id = $model->create($insert);
            $return = ['id'=> $id, 'openid'=> $session['openid']];
        }else{
            //更新登录时间
            $update = ['id' => $user['id'], 'login_at' => Carbon::now()];
            $model->update($update);
            $return = ['id'=> $user['id'], 'openid'=> $session['openid']];
        }
        return $this->writeJson(0,['user'=>$return],'SECCUSS');
    }

}
